package com.yanqu.road.server.channelserver.cmd.server;

import com.yanqu.road.NettyMgr;
import com.yanqu.road.define.YanQuNettyDefine;
import com.yanqu.road.connect.YanQuConnection;
import com.yanqu.road.pb.server.LoadProto;
import com.yanqu.road.server.channelserver.manager.server.ChannelRegisterServerMgr;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.server.connect.ChannelCross3LinkedControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import io.netty.channel.ChannelHandlerContext;

@Cmd(code = Protocol.N_REGISTER, desc = "注册服务器")
public class RegisterChannelServerCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {
        LoadProto.LoadChannelMsg reqMsg = LoadProto.LoadChannelMsg.parseFrom(packet.toByteArray());
        long serverId = reqMsg.getServerId();
        int serverIndex = reqMsg.getServerIndex();
        int linkIndex = reqMsg.getLinkIndex();
        int channelId = reqMsg.getChannelId();

        YanQuConnection connection = new YanQuConnection(ctx.channel(), true, 1024, linkIndex);
        ChannelCross3LinkedControl.init(serverId, 1);
        ServerConnectionGroup group = ChannelCross3LinkedControl.addCrossLinkedGroup(serverId, serverIndex, connection, YanQuNettyDefine.LINK_COUNT_MAX, linkIndex);
        ctx.channel().attr(NettyMgr.LINKED_CLIENT).set(group);

        ChannelRegisterServerMgr.addCross3Id(channelId, serverId);
    }

}
